import loadingBar from './loading-bar'

var toastInstance = null

function newInstance() {
  var div = document.createElement('div')
  div.innerHTML = '<loading-bar></loading-bar>'
  document.body.appendChild(div)

  var loading_bar = new Vue({
    el: div,
    components: { loadingBar }
  }).$children[0]

  return {
    update(options) {
      loading_bar.update(options)
    },
    destory() {
      document.body.removeChild(div)
    }
  }
}

function getToastInstance() {
  toastInstance = toastInstance || newInstance()

  return toastInstance
}

function start() {
  getToastInstance()
  toastInstance.update({ state: 'start' })
}

function error(tips) {
  getToastInstance()
  toastInstance.update({
    tips,
    state: 'error'
  })
}

function end(tips) {
  getToastInstance()
  toastInstance.update({
    tips,
    state: 'end'
  })
}

function finish() {
  getToastInstance()
  toastInstance.update({ state: 'finish' })
}

function destory() {
  ;
  var instance = getToastInstance()
  toastInstance = null
  instance.destory()
}

export default {
  start,
  error,
  end,
  finish,
  destory
}
